/*
 * @Author: your name
 * @Date: 2021-06-08 12:30:28
 * @LastEditTime: 2021-06-15 09:39:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \UDP\SERVER_\serversocket.cpp
 */
#include "serversocket.h"


Serversocket::Serversocket(char* str_port)
{
    //判断端口号
    int port = atoi(str_port);
    if( port<1025 || port>65535 )//0~1024一般给系统使用，一共可以分配到65535
	{
		printf("端口号范围应为1025~65535");
		exit(-1);
	}

    //创建udp通信socket
	m_udp_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(m_udp_socket_fd == -1)
	{
		perror("socket failed!\n");
		exit(-1);
	}

    //设置目的IP地址
    m_local_addr = {0};
    m_local_addr.sin_family = AF_INET;//使用IPv4协议
    m_local_addr.sin_port = htons(port);//设置接收方端口号
    m_local_addr.sin_addr.s_addr = INADDR_ANY;//让系统检测本地网卡，自动绑定本地IP

    //将程序与端口绑定
    int ret = bind(m_udp_socket_fd,(struct sockaddr*)&m_local_addr,sizeof(m_local_addr));
	if(ret < 0)
	{
		perror("bind fail:");
		close(m_udp_socket_fd);
		exit(-1);
	}
	else
	{
		printf("recv ready!!!\n");
	}
}

Serversocket::~Serversocket()
{
    //关闭udp通信
    close(m_udp_socket_fd);
}

void Serversocket::clear_Cache()
{
    memset(send_buf,0,MAX_INFO_SIZE);
    memset(recv_buf,0,MAX_INFO_SIZE);
}

bool Serversocket::send_To_Client()
{
    //向接收到的源发送信息
    sendto(m_udp_socket_fd, send_buf, send_length, 0, (struct sockaddr *)&m_src_addr,sizeof(m_src_addr)); 
}

bool Serversocket::recv_From_Client()
{
	//接收信息
	socklen_t len = sizeof(m_src_addr);
	recv_length = recvfrom(m_udp_socket_fd, recv_buf, MAX_INFO_SIZE , 0, (struct sockaddr *)&m_src_addr, &len);
	if(recv_length == -1)
	{
		return false;
	}
	// cout << "recv_length:" << recv_length << endl;sizeof(recv_buf)
	// printf("[%s:%d]\n",inet_ntoa(m_src_addr.sin_addr),ntohs(m_src_addr.sin_port));//打印消息发送方的ip与端口号
	return true;
}
